package org.spring.demo.interceptor;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.slf4j.LoggerFactory;
import org.spring.demo.entity.SysUser;
import org.spring.demo.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 拦截器
 * @author zp
 * @date   2018年9月13日
 */
public class MyInterceptor implements HandlerInterceptor{
	
     
	 @Autowired
	 private SysUserService sysUserService;
	 private static final org.slf4j.Logger logger = LoggerFactory.getLogger(MyInterceptor.class);
	    @Override
		public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		    long startTime = System.currentTimeMillis();
		    request.setAttribute("startTime", startTime);
		    HttpSession session = request.getSession();
		    session.setAttribute("userName", "张三");
		    if (handler instanceof HandlerMethod) {
		        StringBuilder sb = new StringBuilder(1000);
		        HandlerMethod h = (HandlerMethod) handler;
		        sb.append("AskDate   : ").append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())).append("\n");
		        sb.append("Controller: ").append(h.getBean().getClass().getName()).append("\n");
		        sb.append("Method    : ").append(h.getMethod().getName()).append("\n");
		        sb.append("Params    : ").append(getParamString(request.getParameterMap())).append("\n");
		        sb.append("URI       : ").append(request.getRequestURI()).append("\n");
		        sb.append("User      : ").append(session.getAttribute("userName")).append("\n");
		        System.out.println(sb.toString());
		        SysUser uesr= sysUserService.selectByPrimaryKey(1l);
		        logger.info("日志所开始--------------------->:{}", sb.toString());
		    }
		    return true;
		}

		@Override
		public void postHandle(HttpServletRequest request,
		                       HttpServletResponse response, Object handler,
		                       ModelAndView modelAndView) throws Exception {
		    long startTime = (Long) request.getAttribute("startTime");
		    long endTime = System.currentTimeMillis();
		    long executeTime = endTime - startTime;
		    if (handler instanceof HandlerMethod) {
		        StringBuilder sb = new StringBuilder(1000);
		        sb.append("-----------------------------------------------").append("\n");
		        sb.append("CostTime  : ").append(executeTime).append("ms").append("\n");
		        sb.append("-----------------------------------------------");
		        System.out.println(sb.toString());
		    }
		}

		private String getParamString(Map<String, String[]> map) {
		    StringBuilder sb = new StringBuilder();
		    for (Entry<String, String[]> e : map.entrySet()) {
		        sb.append(e.getKey()).append("=");
		        String[] value = e.getValue();
		        if (value != null && value.length == 1) {
		            sb.append(value[0]).append("\t");
		        } else {
		            sb.append(Arrays.toString(value)).append("\t");
		        }
		    }
		    return sb.toString();
		}

		@Override
		public void afterCompletion(HttpServletRequest arg0,HttpServletResponse arg1, Object arg2, Exception arg3)
		        throws Exception {
		}
}
